﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Server
{
    public class ConfigModel
    {
        public int ServerPort { get; set; }
        public bool AutoRun { get; set; }
        public bool AutoStart { get; set; }
        public bool AutoMin { get; set; }

        public ConfigModel()
        {
            ServerPort = 59999;
            AutoRun = false;
            AutoStart = false;
            AutoMin = false;
        }

        public void ReadConfig(string path)
        {
            try
            {
                CheckCfgFile(path);
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(path);
                XmlNode root = xDoc.SelectSingleNode("Config");
                CheckNode(root);
                XmlNode xn = root.SelectSingleNode("AutoRun");
                CheckNode(xn);
                AutoRun = Convert.ToBoolean(xn.InnerText);
                xn = root.SelectSingleNode("AutoStart");
                CheckNode(xn);
                AutoStart = Convert.ToBoolean(xn.InnerText);
                xn = root.SelectSingleNode("AutoMin");
                CheckNode(xn);
                AutoMin = Convert.ToBoolean(xn.InnerText);
                xn = root.SelectSingleNode("ServerPort");
                CheckNode(xn);
                ServerPort = Convert.ToInt32(xn.InnerText);
            }
            catch (Exception)
            {
                ServerPort = 59999;
                AutoRun = false;
                AutoStart = false;
                AutoMin = false;
                SaveConfig(path);
            }
        }

        private void CheckCfgFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new Exception();
            }
        }

        private void CheckNode(XmlNode xn)
        {
            if (xn is null)
                throw new Exception("未找到指定节点");
        }

        public void SaveConfig(string path)
        {
            XmlDocument xDoc = new XmlDocument();
            XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xDoc.AppendChild(xDec);
            XmlElement root = xDoc.CreateElement("Config");
            XmlElement xl = xDoc.CreateElement("AutoRun");
            xl.InnerText = AutoRun.ToString();
            root.AppendChild(xl);
            xl = xDoc.CreateElement("AutoStart");
            xl.InnerText = AutoStart.ToString();
            root.AppendChild(xl);
            xl = xDoc.CreateElement("AutoMin");
            xl.InnerText = AutoMin.ToString();
            root.AppendChild(xl);
            xl = xDoc.CreateElement("ServerPort");
            xl.InnerText = ServerPort.ToString();
            root.AppendChild(xl);
            xDoc.AppendChild(root);
            xDoc.Save(path);
        }
    }
}